import requests
import json
# 读取cityid.txt文件内容
sheng=""
shi=""
xian=""
with open('/home/pi-star/mmdvm-wendu/cityid.txt', 'r',encoding='GBK') as f:
    sheng = f.readline().strip() # 读取第一行(省)
    shi = f.readline().strip() # 读取第二行(市)
    xian = f.readline().strip() # 读取第三行(县)
# 打印读取到的内容
#    print("省：%s" % sheng)
 #   print("市：%s" % shi)
  #  print("县：%s" % xian)
    #with open('weather.txt', 'w', encoding='utf-8') as f:
        #f.write("%s\n"% sheng)
        #f.write("%s\n"% shi)
        #f.write("%s\n"% xian)
url_template = "https://wis.qq.com/weather/common?source=pc&weather_type=observe&province={}&city={}&county={}"
url = url_template.format(sheng, shi, xian)
#print(url)
response = requests.get(url)
#print(response)
if response.status_code == 200:
    try:
        jsondata=response.json()
       # print(jsondata)
        data = jsondata.get('data',{})
       # print(data)
        observe=data.get('observe',{})
       # print(observe)
        weather_info = "当前天气：{weather},温度{degree}℃,湿度{humidity}%,{wind}{power}级".format(
        weather=observe['weather'],
        degree=observe['degree'],
        humidity=observe['humidity'],
        wind=observe['wind_direction_name'],
        power=observe['wind_power'])
        #print(weather_info)
        with open('/home/pi-star/mmdvm-wendu/weather.txt', 'w', encoding='utf-8') as file:
            file.write(weather_info)        
        print("天气数据已写入weather.txt文件。")
    except ValueError:
        print("响应数据不是有效的JSON格式。")
else:
    print("请求失败，状态码: {response.status_code}")

